from flask import current_app
from flask_login import current_user
from sqlalchemy import Column, String, Integer, ForeignKey, Boolean, func
from sqlalchemy.orm import relationship

from apps.spider.yushu_book import YuShuBook
from .base import db, Base


class Gift(Base):
    __tablename__ = 'gift'

    id = Column(Integer, primary_key=True)
    user = relationship('User')
    uid = Column(Integer, ForeignKey('user.id'), nullable=False)
    isbn = Column(String(13), nullable=False)
    launched = Column(Boolean, default=False)

    @property
    def book(self):
        yushu_book = YuShuBook()
        yushu_book.search_by_isbn(self.isbn)
        return yushu_book.first

    @classmethod
    def recent(cls, uid):
        recent_gifts = Gift.query.filter_by(uid=uid,launched=False).group_by(
            Gift.isbn).order_by(
            Gift.create_time.desc()).limit(
            current_app.config['RECENT_GIFT_COUNT']).distinct().all()
        return recent_gifts

    @classmethod
    def get_user_gift(cls, isbn_list):
        from apps.models.wish import Wish
        single_gift_count = db.session.query(Wish.isbn, func.count(Wish.id)
                                             ).filter(Wish.launched == False,
                                                      Wish.status == 1, Wish.isbn.in_(isbn_list)
                                                      ).group_by(Wish.isbn
                                                                 ).all()
        gift_count_list = [{'isbn': x[0], 'count': x[1]} for x in single_gift_count] if single_gift_count else []
        return gift_count_list
